package cn.fl.mcr.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.dto.MessageDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.user.facade.system.dto.SysUsrDatAuthRDTO;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.mcr.constant.McrBillMConstant;
import cn.fl.mcr.service.IMcrBillMService;
import cn.fl.mcr.transform.McrBillMVOTransform;
import cn.fl.mcr.vo.McrBillMVO;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.base.constant.BaseConstant;
import cn.lionbridgecapital.loan.model.condition.GraphicReportQC;
import cn.lionbridgecapital.loan.model.condition.McrBillMQC;
import cn.lionbridgecapital.loan.model.condition.McrInformTransferQC;
import cn.lionbridgecapital.loan.model.condition.McrYlCompensatFlowQC;
import cn.lionbridgecapital.loan.model.dto.McrBillMDTO;
import cn.lionbridgecapital.loan.model.dto.McrInformTransferDTO;
import cn.lionbridgecapital.loan.model.exception.BaseExceptionConstant;
import cn.lionbridgecapital.loan.model.po.McrBillM;
import cn.lionbridgecapital.loan.model.po.McrYlCompensatFlow;
import cn.lionbridgecapital.loan.service.api.IMcrBillMApiService;
import cn.lionbridgecapital.loan.service.api.IMcrInformTransferApiService;
import cn.lionbridgecapital.loan.service.api.IMcrYLBillApiService;

import com.alibaba.fastjson.JSONObject;
import fl.yntrust.facade.api.IYnTrustApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 小贷账单主表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class McrBillMServiceImpl implements IMcrBillMService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(McrBillMServiceImpl.class);
	
	/**
	 * 小贷账单主表 暴露服务
	 */
	@Autowired
	private IMcrBillMApiService publicMcrBillMApiService;
    @Autowired
    private cn.fl.mcr.api.IMcrBillMApiService  mcrBillMApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private IMcrInformTransferApiService publicMcrInformTransferApiService;

    @Autowired
    private IYnTrustApi ynTrustApi;
    @Autowired
    private IMcrYLBillApiService mcrYLBillApiService;
    
    
	@Override
	public McrBillMVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		McrBillMDTO dto = this.publicMcrBillMApiService.selectMcrBillMById(id);
        McrBillMVO vo = McrBillMVOTransform.toVO(dto);
        this.setDictData(vo);
        return vo;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        McrBillMQC condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new McrBillMQC());
        }
		condition=(McrBillMQC)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		page=this.publicMcrBillMApiService.searchMcrBillMListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<McrBillMVO> voList=McrBillMVOTransform.toVOList((List<McrBillMDTO>)page.getResultList());
            //格式化保留两位小数
            DecimalFormat df = new DecimalFormat("######0.00");
            for (McrBillMVO vo : voList) {
                McrInformTransferQC qc =new McrInformTransferQC();
                qc.setPrjId(vo.getId());
                qc.setIsValid(1);
                List<McrInformTransferDTO> ferList = publicMcrInformTransferApiService.searchMcrInformTransferDTOList(qc);
                if(CollectionUtils.isNotEmpty(ferList)){
                    McrInformTransferDTO ferDto = ferList.get(0);
                    vo.setLoanAccountName(ferDto.getLoanChannel());
                    vo.setCapAmt(df.format(DecimalUtils.convertFenToYuan(ferDto.getCapAmt())));
                    vo.setIntrAmt(df.format(DecimalUtils.convertFenToYuan(ferDto.getIntrAmt())));
                    vo.setPenaltyAmt(df.format(DecimalUtils.convertFenToYuan(ferDto.getPenaltyAmt())));
                    vo.setTotalAmt(df.format(DecimalUtils.convertFenToYuan(ferDto.getTotalAmt())));
                }
                
                McrYlCompensatFlowQC compensatFlowQc = new McrYlCompensatFlowQC();
                compensatFlowQc.setCrCntNo(vo.getCrCntNo());
                List<McrYlCompensatFlow> compensatFlowList =  mcrYLBillApiService.searchCompensatFlowList(compensatFlowQc);
                if(CollectionUtils.isNotEmpty(compensatFlowList)) {
                	McrYlCompensatFlow mcrYlCompensatFlow = compensatFlowList.get(0);
                	Date compensatTime = mcrYlCompensatFlow.getCompensatTime();
                	if(null != compensatTime) {
                		vo.setBuyBackSuccDate(DateUtils.formatDateToString(compensatTime, DateUtils.YYYY_MM_DDHHMMSS) );
                	}
                }
            }
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<McrBillMVO> searchList(McrBillMQC condition) throws BaseException{
		if(null == condition) condition=new McrBillMQC();
		List<McrBillMVO> voList=McrBillMVOTransform.toVOList(this.publicMcrBillMApiService.searchMcrBillMList(condition));
		this.setDictData(voList);
		return voList;
	}
	
    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<McrBillMVO> voList){
        if(CollectionUtils.isEmpty(voList)) return;
        Map<String, String> crTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrBillMConstant.SYS_DIC_CR_TYP_CD);
        Map<String, String> loanStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrBillMConstant.SYS_DIC_LOAN_STS_CD);
        Map<String, String> loanBizTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        Map<String, String> crPdUntCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CR_PD_UNT_CD);
        Map<String, String> rateTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(),DictionaryConstant.RATE_TYP_CD);
        //格式化保留两位小数
        DecimalFormat df = new DecimalFormat("######0.00");

        for(McrBillMVO vo:voList){
            if (crTypCdMap != null && crTypCdMap.containsKey(vo.getCrTypCd())) {
                vo.setCrTypCdNm(crTypCdMap.get(vo.getCrTypCd()));
            }
            if (loanStsCdMap != null && loanStsCdMap.containsKey(vo.getLoanStsCd())) {
                vo.setLoanStsCdNm(loanStsCdMap.get(vo.getLoanStsCd()));
            }
            if (loanBizTypCdMap != null && loanBizTypCdMap.containsKey(vo.getLoanBizTypCd())) {
                vo.setLoanBizTypCdNm(loanBizTypCdMap.get(vo.getLoanBizTypCd()));
            }
            if (crPdUntCdMap != null && crPdUntCdMap.containsKey(vo.getCrPdUntCd())) {
                vo.setCrPdUntCdNm(crPdUntCdMap.get(vo.getCrPdUntCd()));
            }
            if (rateTypCdMap != null && rateTypCdMap.containsKey(vo.getRateTypCd())) {
                vo.setRateTypCdNm(rateTypCdMap.get(vo.getRateTypCd()));
            }

            if(null != vo.getCrDt()){
                vo.setCrDtStr(DateUtils.formatDateToString(vo.getCrDt(),DateUtils.YYYY_MM_DD));
            }
            if(null != vo.getStlDt()){
                vo.setStlDtStr(DateUtils.formatDateToString(vo.getStlDt(),DateUtils.YYYY_MM_DD));
            }
            if(StringUtils.isNotEmpty(vo.getActCrAmt())){
                vo.setActCrAmtStr(df.format(DecimalUtils.convertFenToYuan(vo.getActCrAmt())));
            }
            if(StringUtils.isNotEmpty(vo.getCrAmt())){
                vo.setCrAmtStr(df.format(DecimalUtils.convertFenToYuan(vo.getCrAmt())));
            }
            if(StringUtils.isNotEmpty(vo.getRntAmt())){
                vo.setRntAmtStr(df.format(DecimalUtils.convertFenToYuan(vo.getRntAmt())));
            }
        }
    }

    public void setDictData(McrBillMVO vo){
        if(null == vo) return;
        Map<String, String> crTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrBillMConstant.SYS_DIC_CR_TYP_CD);
        Map<String, String> loanStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrBillMConstant.SYS_DIC_LOAN_STS_CD);
        Map<String, String> loanBizTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), McrBillMConstant.SYS_DIC_LOAN_BIZ_TYP_CD);
        Map<String, String> crPdUntCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CR_PD_UNT_CD);
        Map<String, String> rateTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(),DictionaryConstant.RATE_TYP_CD);
        //格式化保留两位小数
        DecimalFormat df = new DecimalFormat("######0.00");
        if (crTypCdMap != null && crTypCdMap.containsKey(vo.getCrTypCd())) {
            vo.setCrTypCdNm(crTypCdMap.get(vo.getCrTypCd()));
        }
        if (loanStsCdMap != null && loanStsCdMap.containsKey(vo.getLoanStsCd())) {
            vo.setLoanStsCdNm(loanStsCdMap.get(vo.getLoanStsCd()));
        }
        if (loanBizTypCdMap != null && loanBizTypCdMap.containsKey(vo.getLoanBizTypCd())) {
            vo.setLoanBizTypCdNm(loanBizTypCdMap.get(vo.getLoanBizTypCd()));
        }
        if (crPdUntCdMap != null && crPdUntCdMap.containsKey(vo.getCrPdUntCd())) {
            vo.setCrPdUntCdNm(crPdUntCdMap.get(vo.getCrPdUntCd()));
        }
        if (rateTypCdMap != null && rateTypCdMap.containsKey(vo.getRateTypCd())) {
            vo.setRateTypCdNm(rateTypCdMap.get(vo.getRateTypCd()));
        }

        if(null != vo.getCrDt()){
            vo.setCrDtStr(DateUtils.formatDateToString(vo.getCrDt(),DateUtils.YYYY_MM_DD));
        }
        if(null != vo.getStlDt()){
            vo.setStlDtStr(DateUtils.formatDateToString(vo.getStlDt(),DateUtils.YYYY_MM_DD));
        }
        if(StringUtils.isNotEmpty(vo.getActCrAmt())){
            vo.setActCrAmtStr(df.format(DecimalUtils.convertFenToYuan(vo.getActCrAmt())));
        }
        if(StringUtils.isNotEmpty(vo.getCrAmt())){
            vo.setCrAmtStr(df.format(DecimalUtils.convertFenToYuan(vo.getCrAmt())));
        }
        if(StringUtils.isNotEmpty(vo.getRntAmt())){
            vo.setRntAmtStr(df.format(DecimalUtils.convertFenToYuan(vo.getRntAmt())));
        }
    }
	
	/**
     * 查询数据字典
     * @param groupCd 组代码
     * @return List<KeyValueVO>
     */
    public List<KeyValueVO> searchCdList(String groupCd){
        return this.sysDictionaryApiService.getKvList(groupCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    @Override
    public Pager searchOvdListPage(Pager page) throws BaseException{
        McrBillMQC condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new McrBillMQC());
        }
        condition=(McrBillMQC)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        page=this.publicMcrBillMApiService.searchMcrOvdBillListPage(page);
        if(null != page && CollectionUtils.isNotEmpty(page.getResultList())){
            List<McrBillMVO> voList=McrBillMVOTransform.toVOList((List<McrBillMDTO>)page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
    }

    @Override
    public List<McrBillMVO> searchList(cn.fl.mcr.condition.McrBillMQC condition) throws BaseException{
        if(null == condition) condition=new cn.fl.mcr.condition.McrBillMQC();
        List<cn.fl.mcr.dto.McrBillMDTO> list = this.mcrBillMApiService.searchMcrBillMList(condition);
        List<McrBillMVO> voList=McrBillMVOTransform.toVoList(list);
        this.setDictData(voList);
        return voList;
    }


    @Override
    public DataResultDTO pushRepaymentPlan() throws BaseException {
        BaseLogUtils.info(logger,"pushRepaymentPlan","推送还款计划.开始推送还款计划");
        DataResultDTO resultDTO = new DataResultDTO(BaseConstant.IS_YESNO_YES, "还款计划推送成功");
        try{
            resultDTO = mcrBillMApiService.pushRepaymentPlan();
            if(resultDTO != null && resultDTO.getSuccess() == BaseConstant.IS_YESNO_YES){
                resultDTO.setInfo("还款计划推送成功");
            }else{
                resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultDTO.setInfo("还款计划推送异常");
            }
        }catch (BaseException be){
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo("还款计划推送异常");
            BaseLogUtils.error(logger,"pushRepaymentPlan","推送还款计划.异常："+be.getMessage());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601,"推送还款计划异常");
        }catch (Exception e){
            resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultDTO.setInfo("还款计划推送异常");
            BaseLogUtils.error(logger,"pushRepaymentPlan","推送还款计划.异常："+e.getMessage());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601,"推送还款计划异常");
        }

        BaseLogUtils.info(logger,"pushRepaymentPlan","推送还款计划.推送还款计划结束");
        return resultDTO;
    }

	@Override
	public List<McrBillM> queryMcrBillMLActCrAmt(GraphicReportQC condition) throws BaseException {
		return publicMcrBillMApiService.queryMcrBillMLActCrAmt(condition);
	}

	@Override
	public HashMap<String, Object> selectRecvRent(GraphicReportQC condition) throws BaseException {
		// TODO Auto-generated method stub
		return publicMcrBillMApiService.selectRecvRent(condition);
	}

}
